package cn.iocoder.yudao.module.of.service.taskhandler;

import cn.iocoder.yudao.framework.common.core.SysConstants;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.of.controller.admin.taskfeedback.vo.AddTaskInterfaceUserReq;
import cn.iocoder.yudao.module.of.controller.admin.taskhandler.vo.TaskHandlerRespVO;
import cn.iocoder.yudao.module.of.controller.admin.taskhandler.vo.TaskHandlerSaveReqVO;
import cn.iocoder.yudao.module.of.dal.dataobject.taskhandler.TaskHandlerDO;
import cn.iocoder.yudao.module.of.dal.mysql.taskhandler.TaskHandlerMapper;
import cn.iocoder.yudao.module.of.enums.HandlerTypeEnum;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.of.enums.ErrorCodeConstantsOfTask.ADD_TASK_INTERFACE_USER_ERR;
import static cn.iocoder.yudao.module.of.enums.ErrorCodeConstantsOfTask.ADD_TASK_INTERFACE_USER_NOT_PERMISSION;

/**
 * 任务办理人员 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class TaskHandlerServiceImpl implements TaskHandlerService {

    @Resource
    private TaskHandlerMapper taskHandlerMapper;
    @Resource
    private AdminUserMapper userMapper;

    @Override
    public void createTaskHandler(Long taskId, List<TaskHandlerSaveReqVO> list) {
        List<TaskHandlerDO> collect = list.stream().map(item -> {
            TaskHandlerDO bean = BeanUtils.toBean(item, TaskHandlerDO.class);
            bean.setTaskId(taskId);
            if (item.getLeaderUserId() != null) {
                bean.setUserId(item.getLeaderUserId());
            }
            return bean;
        }).collect(Collectors.toList());

        taskHandlerMapper.insertBatch(collect);
    }

    /**
     * 更新任务办理人员
     */
    @Override
    public void updateTaskHandler(Long taskId, List<TaskHandlerSaveReqVO> list) {
        LambdaUpdateWrapper<TaskHandlerDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TaskHandlerDO::getTaskId, taskId);
        taskHandlerMapper.delete(updateWrapper);

        List<TaskHandlerDO> collect = list.stream().map(item -> {
            TaskHandlerDO bean = BeanUtils.toBean(item, TaskHandlerDO.class);
            bean.setTaskId(taskId);
            if (item.getLeaderUserId() != null) {
                bean.setUserId(item.getLeaderUserId());
            }
            return bean;
        }).collect(Collectors.toList());

        taskHandlerMapper.insertBatch(collect);
    }

    @Override
    public void deleteTaskHandler(Long taskId) {
        // 删除
        LambdaUpdateWrapper<TaskHandlerDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TaskHandlerDO::getTaskId, taskId);
        taskHandlerMapper.delete(updateWrapper);
    }


    /**
     * 获得任务办理人员
     *
     * @param taskId 任务编号
     * @return 任务办理人员
     */
    @Override
    public List<TaskHandlerRespVO> getTaskHandler(Long taskId) {
        MPJLambdaWrapper<TaskHandlerDO> query = new MPJLambdaWrapper<>();
        query.selectAll(TaskHandlerDO.class);
        query.selectAs(DeptDO::getName, TaskHandlerRespVO::getDeptName);
        query.selectAs(AdminUserDO::getNickname, TaskHandlerRespVO::getUserName);
        query.eq(TaskHandlerDO::getTaskId, taskId);
        query.leftJoin(DeptDO.class, DeptDO::getId, TaskHandlerDO::getDeptId);
        query.leftJoin(AdminUserDO.class, AdminUserDO::getId, TaskHandlerDO::getUserId);


        List<TaskHandlerRespVO> taskHandlerRespVOS = taskHandlerMapper.selectJoinList(TaskHandlerRespVO.class, query);

        taskHandlerRespVOS.forEach(item -> {
            // 集团显示主办人
            // 子公司显示接口人,没有显示主办人
            if (item.getTenantId().equals(SysConstants.TOP_TENANT_ID)) {
                item.setShowName(item.getUserName());
                item.setCompanyLevel(1);
            } else {
                item.setCompanyLevel(2);
                if (item.getDistributionUserId() != null) {
                    item.setShowName(item.getDistributionUserName());
                } else {
                    item.setShowName(item.getUserName());
                }
            }

            // 获得接口人信息
            if (item.getDistributionUserId() != null) {
                AdminUserDO adminUserDO = userMapper.selectById(item.getDistributionUserId());
                if (adminUserDO != null) {
                    item.setDistributionUserName(adminUserDO.getNickname());
                }
            }
        });

        return taskHandlerRespVOS;
    }

    /**
     * 获得任务主要办理人员
     * <p>
     * 只有一个
     *
     * @param taskId 任务编号
     * @return 任务办理人员
     */
    @Override
    public List<TaskHandlerRespVO> getTaskMainHandler(Long taskId) {
        // 代办人为空，则查询不出来
        /*MPJLambdaWrapper<TaskHandlerDO> query = new MPJLambdaWrapper<>();
        query.selectAll(TaskHandlerDO.class);
        query.selectAs(DeptDO::getName, TaskHandlerRespVO::getDeptName);
        query.selectAs("t2",AdminUserDO::getNickname, TaskHandlerRespVO::getUserName);
        query.selectAs("t3",AdminUserDO::getNickname, TaskHandlerRespVO::getDistributionUserName);

        query.eq(TaskHandlerDO::getTaskId, taskId);
        query.eq(TaskHandlerDO::getHandlerType, HandlerTypeEnum.MASTER_LEVEL.getCode());
        query.leftJoin(DeptDO.class, DeptDO::getId, TaskHandlerDO::getDeptId);
        query.innerJoin(AdminUserDO.class, AdminUserDO::getId, TaskHandlerDO::getUserId);
        query.innerJoin(AdminUserDO.class, AdminUserDO::getId, TaskHandlerDO::getDistributionUserId);*/

        MPJLambdaWrapper<TaskHandlerDO> query = new MPJLambdaWrapper<>();
        query.selectAll(TaskHandlerDO.class);
        query.selectAs(DeptDO::getName, TaskHandlerRespVO::getDeptName);
        query.selectAs(AdminUserDO::getNickname, TaskHandlerRespVO::getUserName);

        query.eq(TaskHandlerDO::getTaskId, taskId);
        query.eq(TaskHandlerDO::getHandlerType, HandlerTypeEnum.MASTER_LEVEL.getCode());
        query.leftJoin(DeptDO.class, DeptDO::getId, TaskHandlerDO::getDeptId);
        query.leftJoin(AdminUserDO.class, AdminUserDO::getId, TaskHandlerDO::getUserId);

        List<TaskHandlerRespVO> taskHandlerRespVOS = taskHandlerMapper.selectJoinList(TaskHandlerRespVO.class, query);

        taskHandlerRespVOS.forEach(item -> {
            // 集团显示主办人
            // 子公司显示接口人,没有显示主办人
            if (item.getTenantId().equals(SysConstants.TOP_TENANT_ID)) {
                item.setShowName(item.getUserName());
                item.setCompanyLevel(1);
            } else {
                item.setCompanyLevel(2);
                if (item.getDistributionUserId() != null) {
                    item.setShowName(item.getDistributionUserName());
                } else {
                    item.setShowName(item.getUserName());
                }
            }
            // 获得接口人信息
            if (item.getDistributionUserId() != null) {
                AdminUserDO adminUserDO = userMapper.selectById(item.getDistributionUserId());
                if (adminUserDO != null) {
                    item.setDistributionUserName(adminUserDO.getNickname());
                    if (item.getCompanyLevel() == 2) {
                        item.setShowName(adminUserDO.getNickname());
                    }
                }
            }
        });

        return taskHandlerRespVOS;
    }

    /**
     * 集团部门领导，添加任务办理人
     *
     * @param req 请求体
     */
    @Override
    public void addTaskInterfaceUser(AddTaskInterfaceUserReq req) {
        Long userId = WebFrameworkUtils.getLoginUserId();


        LambdaUpdateWrapper<TaskHandlerDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TaskHandlerDO::getTaskId, req.getTaskId());
        updateWrapper.eq(TaskHandlerDO::getUserId, userId);

        TaskHandlerDO taskHandlerDO = taskHandlerMapper.selectOne(updateWrapper);
        if (taskHandlerDO == null) {
            throw exception(ADD_TASK_INTERFACE_USER_NOT_PERMISSION);
        }

        int update = taskHandlerMapper.update(new TaskHandlerDO().setDistributionUserId(req.getDistributionUserId()), updateWrapper);

        if (update < 1) {
            throw exception(ADD_TASK_INTERFACE_USER_ERR);
        }

    }

}